package com.codewsq.exer;


/**
 * 数组的增上改查操作
 *
 * @author codewsq
 * @date 2021/5/27 0027 10:42
 */
public class  ArraysCRUD {

    private String[] strs;
    private int total;

    public ArraysCRUD(int arrayLength) {
        this.strs = new String[arrayLength];
    }

    /**
     * 给数组添加元素
     *
     * @param
     * @return boolean
     * @author codewsq
     * @date 2021/5/27 0027 10:46
     */
    public boolean add(String str) {
        if (total >= strs.length) {
            throw new RuntimeException("数组已满");
        }
        strs[total] = str;
        total++;
        return true;
    }

    /**
     * 将元素添加到数组的指定位置
     *
     * @param index str
     * @return boolean
     * @author codewsq
     * @date 2021/5/27 0027 10:50
     */
    public boolean add(int index, String str) {
        if (total >= strs.length) {
            throw new RuntimeException("数组已满");
        }
        if (index < 0 || index >= total) {
            throw new RuntimeException("数组下标越界");
        }

        for (int i = total; i > index; i--) {
            strs[i] = strs[i - 1];
        }
        strs[index] = str;
        total++;
        return true;
    }

    /**
     * 修改数组指定下标的元素
     *
     * @param index str
     * @return boolean
     * @author codewsq
     * @date 2021/5/27 0027 10:54
     */
    public boolean update(int index, String str) {
        if (index < 0 || index >= total) {
            throw new RuntimeException("数组下标元素不存在");
        }
        strs[index] = str;
        return true;
    }

    public boolean delete(int index) {
        if (index < 0 || index >= total) {
            throw new RuntimeException("数组下标元素不存在");
        }
        for (int i = index; i < total; i++) {
            strs[i] = strs[i + 1];
        }
        strs[total - 1] = null;
        total--;
        return true;
    }

    /**
     * 获取所有的元素信息
     *
     * @param
     * @return java.lang.String[]
     * @author codewsq
     * @date 2021/5/27 0027 11:05
     */
    public String[] getStrs() {
        String[] result = new String[total];
        for (int i = 0; i < total; i++) {
            result[i] = strs[i];
        }
        return result;
    }

    /**
     * 拿到当前元素数量
     *
     * @param
     * @return int
     * @author codewsq
     * @date 2021/5/27 0027 11:06
     */
    public int getTotal() {
        return total;
    }
}
